package com.seeyon.apps.ningbobank.manager;

import cn.hutool.core.lang.Assert;
import com.seeyon.apps.bense.bank.manager.DealPayImpl;
import com.seeyon.apps.collaboration.manager.ColManager;
import com.seeyon.apps.collaboration.po.ColSummary;
import com.seeyon.apps.common.utils.JDBCAgentUtils;
import com.seeyon.cap4.form.bean.FormBean;
import com.seeyon.cap4.form.bean.FormDataMasterBean;
import com.seeyon.ctp.common.AppContext;
import com.seeyon.ctp.common.affair.manager.AffairManager;
import com.seeyon.ctp.common.log.CtpLogFactory;
import com.seeyon.ctp.common.po.template.CtpTemplate;
import com.seeyon.ctp.common.template.manager.TemplateManager;
import com.seeyon.ctp.organization.bo.V3xOrgMember;
import com.seeyon.ctp.organization.manager.OrgManager;
import com.seeyon.ctp.util.ParamUtil;
import com.seeyon.ctp.util.annotation.Inject;
import com.seeyon.ctp.workflow.supernode.SuperNodeResponse;
import com.seeyon.ctp.workflow.supernode.dao.SuperNodeDao;
import com.seeyon.ctp.workflow.supernode.enums.SuperNodeEnums;
import com.seeyon.ctp.workflow.supernode.manager.WorkflowSuperNodeApi;
import com.seeyon.ctp.workflow.supernode.po.SuperNodeControl;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName : NingBoBankSuperNodeManagerImpl
 * @Description : 宁波银行付款超级节点实现类
 * @CreateDate : 2025/7/29 10:27
 * @Author : CheungHowrAn
 * @Version : 1.0.0
 * @PackageName com.seeyon.apps.ningbobank.manager
 * @Project : BSiEE本涩_A8_V9.0SP1
 */
public class NingBoBankSuperNodeManagerImpl implements NingBoBankSuperNodeManager {

    private static final Log log = CtpLogFactory.getLog(NingBoBankSuperNodeManager.class);
    @Inject
    private OrgManager orgManager;
    @Inject
    private ColManager colManager;
    @Inject
    private AffairManager affairManager;
    @Inject
    private SuperNodeDao superNodeDao;
    @Inject
    private WorkflowSuperNodeApi workflowSuperNodeApi;
    @Inject
    private DealPayImpl dealPayImpl;

    /**
     * @MethodName: executeAction
     * @Description: 超级节点事件触发动作
     * @CreateDate: 2025/7/29 10:50
     * @Author: CheungHowrAn
     * @Param superNodeId 超级节点ID
     * @Param formBean 表单Bean
     * @Param formDataMasterBean 表单数据Bean
     * @Return SuperNodeResponse
     */
    @Override
    public SuperNodeResponse executeAction(String superNodeId, FormBean formBean, FormDataMasterBean formDataMasterBean) {
        // 超级节点执行结果 returnCode 一定要赋值 系统默认是往下执行 需要卡住的话要设置为 SuperNodeEnums.RunAction.WAIT.getKey()
        SuperNodeResponse response = new SuperNodeResponse();
        try {
            ColSummary summary = colManager.getColSummaryByFormRecordId(formDataMasterBean.getId());
            //todo 补充业务逻辑
//            String formCode = formBean.getBind().getFormCode();
            TemplateManager templateManager = (TemplateManager) AppContext.getBean("templateManager");
            Long templeteId = summary.getTempleteId();
            CtpTemplate ctpTemplate = templateManager.getCtpTemplate(templeteId);
            String formCode = ctpTemplate.getTempleteNumber();
            log.info("formCode====" + formCode);
            Assert.notBlank(formCode, "未配置表单编号");
            dealPayImpl.processData(formCode, formBean, formDataMasterBean);
            //挂起
            response.setSuccess(true);
            response.setReturnCode(SuperNodeEnums.RunAction.WAIT.getKey());
        } catch (Exception e) {
            log.error("宁波银行付款超级节点执行异常,原因：" + e.getMessage(), e);
            response.setSuccess(false);
            response.setReturnCode(SuperNodeEnums.RunAction.BACK.getKey());
            response.setReturnMsg("宁波银行付款超级节点执行异常 ,原因：" + e.getMessage());
        }
        return response;
    }

    /**
     * @MethodName: operateSuperNode
     * @Description: 操作超级节点
     * @CreateDate: 2025/7/29 10:49
     * @Author: CheungHowrAn
     * @Param superNodeId 超级节点ID
     * @Param runAction 运行动作
     * @Param formDataId(formRecordId) 表单数据ID
     * @Param msg  处理结果  成功就传成功 失败就传失败+原因
     */
    @Override
    public void operateSuperNode(String superNodeId, SuperNodeEnums.RunAction runAction, String formDataId, String msg) {
        try {
            if (StringUtils.isNotBlank(superNodeId)) {
                SuperNodeControl control = superNodeDao.getControl(Long.valueOf(superNodeId));
                int pendingType = control.getPendingType();
                if (pendingType == 3) {
                    String interveneMemberId = control.getDesignatedMemberId();
                    V3xOrgMember member = orgManager.getMemberById(Long.valueOf(interveneMemberId));
                    workflowSuperNodeApi.operateWorkflowEngine(superNodeId, runAction.getKey(), formDataId, member.getId(), member.getName(), msg);
                }
            } else {
                log.info("超级节点ID不能为空！formDataId=" + formDataId);
            }
        } catch (Exception e) {
            log.error("超级节点执行异常", e);
        }
    }

    /**
     * @MethodName: getSuperNodeControlDetail
     * @Description: 根据summaryId获取超级节点ID信息
     * @CreateDate: 2025/10/14 11:10
     * @Author: CheungHowrAn
     * @Param summaryId 流程 summaryId
     * @Param superNodeName 超级节点名称 对应 getNodeId()的值
     * @Return Map<Object>
     */
    public Map<String, Object> getSuperNodeControlDetail(String summaryId,String superNodeName) {
        Map<String, Object> map = new HashMap<>();
        try {
            StringBuffer sql = new StringBuffer();
            sql.append("SELECT ")
                    .append("COL_SUMMARY.ID AS SUMMARY_ID, ")
                    .append("COL_SUMMARY.FORM_RECORDID AS FORM_RECORD_ID, ")
                    .append("WF_SUPERNODE_CONTROL.ID AS SUPER_NODE_ID ")
                    .append("FROM ")
                    .append("COL_SUMMARY ")
                    .append("INNER JOIN CTP_AFFAIR ON COL_SUMMARY.ID = CTP_AFFAIR.OBJECT_ID ")
                    .append("AND CTP_AFFAIR.STATE = '3' ")
                    .append("INNER JOIN WF_SUPERNODE_CONTROL ON WF_SUPERNODE_CONTROL.SUMMARY_ID = COL_SUMMARY.ID ")
                    .append("AND WF_SUPERNODE_CONTROL.WORKITEM_ID = CTP_AFFAIR.SUB_OBJECT_ID ")
                    .append("AND WF_SUPERNODE_CONTROL.NODE_ID = CTP_AFFAIR.ACTIVITY_ID ")
                    .append("AND WF_SUPERNODE_CONTROL.SUPER_NODE_ID = '").append(superNodeName).append("' ")
                    .append("WHERE ")
                    .append("COL_SUMMARY.ID =").append(summaryId);
            log.info("根据summaryId获取超级节点ID信息的sql:" + sql);
            List<Map<String, Object>> query = JDBCAgentUtils.query(sql.toString());
            if (query != null && query.size() > 0) {
                map.put("summaryId", query.get(0).get("summary_id"));
                map.put("formRecordId", query.get(0).get("form_record_id"));
                map.put("superNodeId", query.get(0).get("super_node_id"));
            }
        } catch (Exception e) {
            log.error("获取超级节点详情异常", e);
        }
        return map;
    }

    /**
     * @MethodName: main
     * @Description: 超级节点处理示例
     * @CreateDate: 2025/10/14 11:17
     * @Author: CheungHowrAn
     * @Param args
     */
    public static void main(String[] args) {
        NingBoBankSuperNodeManager ningBoBankSuperNodeManager = (NingBoBankSuperNodeManager) AppContext.getBean("ningBoBankSuperNodeManager");
        Map<String, Object> superNodeDetail = ningBoBankSuperNodeManager.getSuperNodeControlDetail("1623731382980528130", "ningBoBankSuperNodeAction");
        String formRecordId = ParamUtil.getString(superNodeDetail, "formRecordId");
        String superNodeId = ParamUtil.getString(superNodeDetail, "superNodeId");
        //成功处理
        ningBoBankSuperNodeManager.operateSuperNode(superNodeId, SuperNodeEnums.RunAction.FORWARD, formRecordId, "处理成功");
        //失败处理 SuperNodeEnums.RunAction.BACK  回退  或者 SuperNodeEnums.RunAction.WAIT 保持等待挂起 定时任务再次处理
        ningBoBankSuperNodeManager.operateSuperNode(superNodeId, SuperNodeEnums.RunAction.BACK, formRecordId, "处理失败");
    }
}
